<template>
  <div class="profile-container">
    <el-row :gutter="24">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <div class="avatar-container">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :auto-upload="true"
                :http-request="handleAvatarUpload"
                accept="image/*"
              >
                <img
                  v-if="userInfo.avatar"
                  :src="userInfo.avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
            <h2 class="username">{{ userInfo.userName }}</h2>
            <div class="role-tag">
              <el-tag type="success">认证游客</el-tag>
            </div>
          </div>

          <div class="profile-stats">
            <div class="stat-item">
              <span class="stat-value">{{ orderList.length }}</span>
              <span class="stat-label">订单数</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{
                formatDate(userInfo.createdTime)
              }}</span>
              <span class="stat-label">注册时间</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ userInfo.userName }}</span>
              <span class="stat-label">用户名</span>
            </div>
          </div>

          <div class="info-list">
            <div class="info-item">
              <el-icon><Timer /></el-icon>
              <span class="label">注册时间：</span>
              <span>{{ formatDate(userInfo.createdTime) }}</span>
            </div>
            <div class="info-item">
              <el-icon><Phone /></el-icon>
              <span class="label">联系电话：</span>
              <span>{{ formatPhone(userInfo.phone) }}</span>
            </div>
            <div class="info-item">
              <el-icon><Message /></el-icon>
              <span class="label">电子邮箱：</span>
              <span>{{ userInfo.email || "未设置" }}</span>
            </div>
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span class="label">性别：</span>
              <span>{{ formatGender(userInfo.sex) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 账户安全卡片 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>账户安全</span>
            </div>
          </template>
          <div class="security-items">
            <div class="security-item">
              <div class="security-info">
                <el-icon><Lock /></el-icon>
                <span>登录密码</span>
              </div>
              <el-button link type="primary">修改</el-button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <el-icon><Phone /></el-icon>
                <span>手机绑定</span>
              </div>
              <el-tag size="small" type="success">已绑定</el-tag>
            </div>
            <div class="security-item">
              <div class="security-info">
                <el-icon><Message /></el-icon>
                <span>邮箱绑定</span>
              </div>
              <el-button link type="primary">绑定</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑表单 -->
      <el-col :span="16">
        <el-card class="edit-form">
          <template #header>
            <div class="card-header">
              <span>个人信息设置</span>
              <el-button type="primary" @click="submitForm">保存修改</el-button>
            </div>
          </template>

          <el-form
            :model="userForm"
            :rules="rules"
            ref="formRef"
            label-width="80px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="userName">
                  <el-input
                    v-model="userForm.userName"
                    placeholder="请输入用户名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="昵称" prop="nickname">
                  <el-input
                    v-model="userForm.nickname"
                    placeholder="请输入昵称"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="手机号">
                  <el-input
                    :model-value="formatPhone(userForm.phone)"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input
                    v-model="userForm.email"
                    placeholder="请输入电子邮箱"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="userForm.sex">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="个人简介" prop="introduce">
              <el-input
                v-model="userForm.introduce"
                type="textarea"
                :rows="4"
                placeholder="请输入个人简介"
              />
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 订单列表卡片 -->
        <el-card class="orders-card">
          <template #header>
            <div class="card-header">
              <span>我的订单</span>
              <el-radio-group v-model="orderStatus" size="small">
                <el-radio-button label="all">全部</el-radio-button>
                <el-radio-button label="pending">待付款</el-radio-button>
                <el-radio-button label="paid">已付款</el-radio-button>
                <el-radio-button label="completed">已完成</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <el-table :data="paginatedOrders" style="width: 100%">
            <el-table-column prop="id" label="订单号" width="100" />
            <el-table-column prop="createdTime" label="下单时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createdTime) }}
              </template>
            </el-table-column>
            <el-table-column label="商品信息" width="200">
              <template #default="{ row }">
                <div
                  v-for="item in row.shoppingCartRespList"
                  :key="item.id"
                  class="product-item"
                >
                  <el-image
                    :src="item.productAvatar"
                    :preview-src-list="[item.productAvatar]"
                    style="width: 50px; height: 50px; border-radius: 4px"
                  />
                  <div class="product-info">
                    <div class="product-name">{{ item.productName }}</div>
                    <div class="product-meta">
                      <span class="price">¥{{ item.productPrice }}</span>
                      <span class="quantity">x{{ item.quantity }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="订单金额" width="120">
              <template #default="{ row }">
                <span class="total-amount"
                  >¥{{ row.totalAmount.toFixed(2) }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewOrderDetail(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import {
  Plus,
  Timer,
  Phone,
  Message,
  User,
  Lock,
  ArrowUp,
  ArrowDown,
} from "@element-plus/icons-vue";
import request, { type ApiResponse } from "@/utils/request";

// 用户信息接口
interface UserInfo {
  id: number;
  userName: string;
  email: string | null;
  phone: string;
  password: string;
  sex: number;
  avatar: string | null;
  status: any;
  introduce: string | null;
  userType: number;
  createdBy: any;
  createdTime: string | null;
  updateBy: string;
  updateTime: string;
  isDeleted: any;
}

// 订单接口
interface ShoppingCartItem {
  id: number;
  userId: number;
  productId: number;
  quantity: number;
  productName: string;
  productPrice: number;
  productAvatar: string;
  createdTime: string;
  updateTime: string | null;
  isDeleted: number;
}

interface Order {
  id: number;
  customerId: number;
  totalAmount: number;
  createdTime: string;
  updateTime: string | null;
  isDeleted: number;
  shoppingCartRespList: ShoppingCartItem[];
}

// 分页数据接口
interface PageResult<T> {
  records: T[];
  total: number;
  size: number;
  current: number;
}

// 用户信息
const userInfo = ref<UserInfo>({
  id: 0,
  userName: "",
  email: null,
  phone: "",
  password: "",
  sex: 0,
  avatar: null,
  status: null,
  introduce: null,
  userType: 0,
  createdBy: null,
  createdTime: null,
  updateBy: "",
  updateTime: "",
  isDeleted: null,
});

// 用户表单接口
interface UserForm {
  userName: string;
  email: string | null;
  phone: string;
  sex: number;
  avatar: string | null;
  introduce: string | null;
  nickname?: string;
}

// 表单数据
const userForm = ref<UserForm>({
  userName: "",
  email: null,
  phone: "",
  sex: 0,
  avatar: null,
  introduce: null,
  nickname: "",
});

// 订单相关数据
const orderList = ref<Order[]>([]);
const currentPage = ref(1);
const pageSize = ref(4);
const total = ref(0);
const orderStatus = ref("all");

// 分页后的订单列表
const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return orderList.value.slice(start, end);
});

// 表单校验规则
const rules = {
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, message: "用户名长度不能小于2个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入电子邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

// 格式化日期
const formatDate = (date: string | null | undefined) => {
  if (!date) return "未设置";
  return new Date(date).toLocaleDateString();
};

// 格式化手机号
const formatPhone = (phone: string | null | undefined) => {
  if (!phone) return "未设置";
  return "18*******00";
};

// 格式化性别
const formatGender = (sex: number) => {
  if (sex === 1) return "男";
  if (sex === 2) return "女";
  return "未设置";
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await request({
      url: "/user/tourist/queryInfo",
      method: "get",
    });

    if (res.success) {
      userInfo.value = res.data;
      userForm.value = {
        ...res.data,
        phone: "18*******00",
      };
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

// 处理头像上传
const handleAvatarUpload = async (options: any) => {
  const file = options.file;
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error("头像只能是 JPG 或 PNG 格式!");
    return;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return;
  }

  const uploadData = new FormData();
  uploadData.append("uploadFile", file);

  try {
    const res = await request({
      url: "/file/ali/upload",
      method: "post",
      data: uploadData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (res.success) {
      // 同时更新userForm和userInfo中的头像
      userForm.value.avatar = res.data;
      userInfo.value.avatar = res.data;

      // 立即提交更新到后端
      await submitForm();
      ElMessage.success("头像上传成功");
    }
  } catch (error) {
    console.error("上传失败:", error);
    ElMessage.error("头像上传失败");
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 创建一个新对象，去掉phone字段
    const { phone, ...updateData } = userForm.value;

    const res = await request({
      url: "/user/tourist/updateInfo",
      method: "post",
      data: updateData,
    });

    if (res.success) {
      ElMessage.success("保存成功");
      getUserInfo();
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    0: "info", // 待付款
    1: "success", // 已付款
    2: "warning", // 已发货
    3: "success", // 已完成
    4: "danger", // 已取消
  };
  return statusMap[status] || "info";
};

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: "待付款",
    1: "已付款",
    2: "已发货",
    3: "已完成",
    4: "已取消",
  };
  return statusMap[status] || "未知状态";
};

// 获取订单列表
const getOrderList = async () => {
  try {
    const res = await request({
      url: "/user/tourist/queryOrder",
      method: "get",
    });

    if (res.success) {
      orderList.value = res.data;
      total.value = res.data.length;
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
    ElMessage.error("获取订单列表失败");
    orderList.value = [];
    total.value = 0;
  }
};

// 查看订单详情
const viewOrderDetail = (order: any) => {
  // TODO: 实现查看订单详情逻辑
  console.log("查看订单详情:", order);
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

// 监听订单状态变化
watch(orderStatus, () => {
  currentPage.value = 1;
  getOrderList();
});

onMounted(() => {
  getUserInfo();
  getOrderList();
});
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;

  .profile-card {
    margin-bottom: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .profile-header {
      text-align: center;
      padding: 24px 0;

      .avatar-container {
        margin-bottom: 16px;
      }

      .username {
        margin: 12px 0 8px;
        font-size: 20px;
        font-weight: 600;
        color: #333;
      }

      .role-tag {
        margin-top: 8px;
      }
    }

    .profile-stats {
      display: flex;
      justify-content: space-around;
      padding: 20px 0;
      border-top: 1px solid #f0f0f0;
      border-bottom: 1px solid #f0f0f0;
      margin: 0 -20px 20px;

      .stat-item {
        text-align: center;

        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: #333;
          line-height: 1.5;
        }

        .stat-label {
          font-size: 13px;
          color: #909399;
        }
      }
    }

    .info-list {
      padding: 0 12px;

      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        font-size: 14px;

        .el-icon {
          margin-right: 8px;
          font-size: 16px;
          color: #909399;
        }

        .label {
          color: #909399;
          margin-right: 8px;
        }
      }
    }
  }

  .security-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .security-items {
      .security-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .security-info {
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 8px;
            font-size: 16px;
            color: #909399;
          }
        }
      }
    }
  }

  .edit-form {
    margin-bottom: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      span {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
    }
  }

  .orders-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: block;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.product-item {
  display: flex;
  align-items: center;
  padding: 8px 0;

  .product-info {
    margin-left: 12px;
    flex: 1;

    .product-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 4px;
    }

    .product-meta {
      display: flex;
      align-items: center;
      gap: 8px;

      .price {
        color: #f56c6c;
        font-size: 14px;
      }

      .quantity {
        color: #909399;
        font-size: 12px;
        margin-left: 4px;
      }
    }
  }
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
}
</style> 